<div class="col-md-6 col-md-offset-3 topic">
  <input type="hidden" id="topic-id" value="<%= typeof(topic._id) !== 'undefined' ? topic._id : '' %>"/>

  <div class="panel panel-default">
    <div class="panel-heading">
      <div class='header'>
        <% if(topic.advertisingMap) {%>
        <a href="#" class="thumbnail">
          <img src="<%= topic.advertisingMap %>">
        </a>
        <% } %>
        <h3>
          【<%= topic.area %>】<%= topic.title %>
        </h3>
        <div class="meta">
          <span>
            作者 <a href="<%= apiPrefix.page %>/user/<%= topic.author.loginname %>?appId=<%= appId %>"><%= topic.author.loginname %></a>
          </span>
          <% if (topic.create_at != topic.update_at) { %>
            <span>
              最后一次编辑是 <%= topic.update_at %>
            </span>
          <% } %>

          <% if(current_user && (current_user._id === topic.author._id || current_user.isAdmin || current_user.isSupport)) {%>
            <a href="<%= apiPrefix.page %>/zone/<%= topic.zone.key %>/<%= topic.zone.template %>/topic/<%=topic._id %>/edit?zoneId=<%= topic.zone._id%>&appId=<%= appId %>">编辑</a>
          <% } %>
        </div>
        <div class="tags">
          <% if(topic.tags) { %>
              <h5></h5>
          <%    topic.tags.split(',').forEach(function(item) { %>
                <span class="label label-info"><%= item %></span>
          <%  })
             } %>
        </div>
      </div>
    </div>
    <div class="panel-body">
      <% if(topic.isHtml) { %>
      <div class='content'>
      <%- topic.linkedContent %>
      <% } else { %>
      <div class='<%=config.mdType%>-body'>
      <%- markdown(topic.linkedContent) %>
      </div>
      <% } %>
    </div>
    <div class="panel-footer">
      <div class="opts">
        <a class="active" v-if="isCollect" href="javascript:;" v-on:click="onDelCollectTopic"><i class="fa fa-bookmark"></i> 收藏</a>
        <a v-else href="javascript:;" v-on:click="onCollectTopic"><i class="fa fa-bookmark"></i> 收藏</a>
      </div>
    </div>
  </div>

  <div class="panel panel-default" v-if="replies.length > 0">
    <div class="panel-heading">
      评论
    </div>
    <div class="panel-body panel-body-reply">
      <div v-if="replies">
        <div class="reply-panel" v-for="reply in replies">
          <div class="reply-user">
            <a><strong>{{reply.author.loginname}}</strong><span class="reply-user-time">{{reply.create_at_ago}}</span></a>
            <div class="btn-toolbar pull-right" role="toolbar" aria-label="...">
              <div class="btn-group" role="group" aria-label="...">
                <button v-if="currentUserId === reply.author._id"
                        type="button"
                        class="btn btn-default btn-sm"
                  v-on:click="onReplyReply(reply._id, reply.author.loginname)">
                  <span class="glyphicon glyphicon-share-alt" aria-hidden="true"></span>
                </button>
                <button v-if="currentUserId === reply.author._id"
                        type="button"
                        class="btn btn-default btn-sm"
                        v-on:click="onDeleteReply(reply._id)">
                  <span class="glyphicon glyphicon-remove" aria-hidden="true" data-replyid="{{reply._id}}"></span>
                </button>
                <button v-if="currentUserId === reply.author._id"
                        type="button" class="btn btn-default btn-sm" v-on:click="onEditReply(reply._id, reply.content)">
                  <span class="glyphicon glyphicon-edit" aria-hidden="true" data-replyid="{{reply._id}}"></span>
                </button>
              </div>
            </div>
          </div>
          <div class='nongshuoshu-body reply-content'>
            {{{reply.htmlContent}}}
          </div>
        </div>
      </div>
      <div v-else>没有评论</div>
    </div>
  </div>

  <% if (typeof(current_user) !== 'undefined' && current_user) { %>
  <div class='panel panel-default'>
    <div class='panel-heading'>
      <span class='col_fade'>添加回复</span>
    </div>
    <div class='panel-body reply'>
      <div class='form-group'>
        <textarea class='form-control' rows='4' v-model="content"></textarea>
      </div>
      <div class='form-group'>
        <button class="btn btn-default pull-right" v-on:click="onReply">提交</button>
      </div>
      <input type='hidden' name='_csrf' id="_csrf" value='<%= csrf %>'/>
    </div>
  </div>
  <% } else { %>
  <div><a href="/signin">登陆</a>后才能评论</div>
  <% } %>
</div>

<script>
  $(document).ready(function () {
    var appId = $('[name=app-id]').val();
    var pagePrefix = '<%= apiPrefix.page %>';
    var dataPrefix = '<%= apiPrefix.data %>';
    var md = new markdownit()
    var vue = new Vue({
      el: '#app',
      data: {
        currentUserId: "",
        topicId: '',
        isCollect: false,
        replies: [],
        content: '',
        currentPage: 1,
        pages: 1,
        canLoadData: true,
        errorMsg: ''
      },
      methods: {
        getReplies: function(nextPage) {
          $.post(dataPrefix + '/' + vue.topicId + '/replies/data',
            {
              appId: appId,
              _csrf: $('#_csrf').val(),
              currentPage: nextPage
            },
            function (result) {
              vue.canLoadData = true;

              if (result.error) {
                vue.errorMsg = result.error;
                return;
              }

              vue.currentPage = result.data.currentPage || 1;
              vue.pages = result.data.pages || 1;
              vue.authors = result.data.authors || [];
              var replies = result.data.replies || [];
              vue.updateReplies(replies);
          });
        },
        updateReplies: function(replies) {
          replies.forEach( function(item) {
            item.htmlContent = md.render(item.content)
            var index = _.findIndex(vue.authors, function(i) {
              return i._id === item.author_id;
            })

            if (index >= 0) {
              item.author = vue.authors[index];
            }
          })

          replies.forEach( function(item){
            vue.replies.push(item);
          });
        },
        onReply: function () {
          vue.resetMessage();
          $.post(dataPrefix + '/reply/' + vue.topicId + '/reply',
            {
              appId: appId,
              _csrf: $('#_csrf').val(),
              content: vue.content || ''
            },
            function (result) {
              if (result.error) {
                vue.errorMsg = result.error;
                return;
              }

              vue.content = '';
              var newReply = result.data.reply;
              newReply.htmlContent = md.render(newReply.content);
              vue.replies.push(newReply);
          });
        },
        onReplyReply: function (replyId, loginname) {
          var editorDialog = new EditorDialog();
          var atUser = '@' + loginname + ' ';
          editorDialog.init('回复'+atUser, atUser);
          editorDialog.show(function (editedContent) {
            if (editedContent) {
              $.post(dataPrefix + '/reply/' + vue.topicId + '/reply',
                {
                  appId: appId,
                  _csrf: $('#_csrf').val(),
                  reply_id: replyId,
                  content: editedContent
                },
                function (result) {
                if (result.error) {
                  vue.errorMsg = result.error;
                  return;
                }

                var newReply = result.data.reply
                newReply.htmlContent = md.render(newReply.content)
                vue.replies.push(newReply)
              });
            }
          });
        },
        onEditReply: function(replyId, content) {
          var editorDialog = new EditorDialog();
          editorDialog.init('编辑', content);
          editorDialog.show(function (editedContent) {
            if (editedContent) {
              $.post(dataPrefix + '/reply/' + replyId + '/edit',
                {
                  appId: appId,
                  _csrf: $('#_csrf').val(),
                  reply_id: replyId,
                  content: editedContent
                },
                function (result) {
                  if (result.error) {
                    vue.errorMsg = result.error;
                    return;
                  }

                  var index = _.findIndex(vue.replies, function(reply) {
                    if (reply._id === replyId) return true;
                  });

                  vue.replies[index].content = editedContent;
                  vue.replies[index].htmlContent = md.render(editedContent);
              });
            }
          });
        },
        onDeleteReply: function(replyId) {
          $.post(dataPrefix + '/reply/' + replyId + '/delete',
            {
              appId: appId,
              _csrf: $('#_csrf').val(),
              reply_id: replyId
            },
            function (result) {
              if (result.error) {
                vue.errorMsg = result.error;
                return;
              }

              var index = _.findIndex(vue.replies, function(reply) {
                if (reply._id === replyId) return true;
              });

              vue.replies.$remove(vue.replies[index]);
            }
          );
        },
        onCollectTopic: function() {
          $.post(dataPrefix + '/topic/collect',
            {
              appId: appId,
              _csrf: $('#_csrf').val(),
              topicId: vue.topicId
            },
            function(result) {
              if (result.error) {
                vue.errorMsg = result.error;
                return;
              }

              vue.isCollect = true;
            }
          );
        },
        onDelCollectTopic: function() {
          $.post(dataPrefix + '/topic/delCollect',
            {
              appId: appId,
              _csrf: $('#_csrf').val(),
              topicId: vue.topicId
            },
            function(result) {
              if (result.error) {
                vue.errorMsg = result.error;
                return;
              }

              vue.isCollect = false;
            }
          )
        },
        changeToHtml: function() {
          return
        },
        resetMessage: function() {
          vue.errorMsg = '';
          vue.successMsg = '';
        }
      }
    });

    vue.topicId = '<%= typeof(topic) !== "undefined" && topic ? topic._id : "" %>';
    vue.isCollect = <%= typeof(topic) !== "undefined" && topic ? topic.isCollect : false %>;
    vue.currentUserId = '<%= typeof(current_user) !== "undefined" && current_user ? current_user._id : "" %>';

    var scrollButtom = new ScrollButtom();
    scrollButtom.init(function() {
      if (vue.currentPage < vue.pages && vue.canLoadData) {
        vue.canLoadData = false;
        vue.getReplies(vue.currentPage + 1);
      }
    });

    vue.getReplies(vue.currentPage);
  });
</script>
